import logging

from build_feature.extract_npm_different_version_functions.git_repository_factory import GitRepositoryFactory
from build_feature.extract_npm_different_version_functions.utils.common_utils import write_json, get_project_folders, get_processed_projects, record_processed_project
from build_feature.extract_npm_different_version_functions.utils.conversion_data import *
import os
import json
from tqdm import tqdm
import time

def is_directory_empty(directory):
    """检查目录是否为空"""
    return not any(os.scandir(directory))

def main():
    # 获取当前文件的绝对路径
    file_name = os.path.abspath(__file__)
    # 获取当前文件所在的目录
    parent_dir = os.path.dirname(file_name)
    # 获取父级目录中的某个特定文件夹中的 JSON 文件路径
    json_file_path = os.path.join(parent_dir, 'config', 'config.json')
    config = None
    # 读取 JSON 文件内容
    try:
        with open(json_file_path, 'r', encoding='utf-8') as file:
            config = json.load(file)
    except FileNotFoundError:
        print(f'Error: The file {json_file_path} does not exist.')
        return
    except json.JSONDecodeError as e:
        print(f'Error parsing the JSON file: {e}')
        return
    except Exception as e:
        print(f'An unexpected error occurred: {e}')
        return

    target_dir = config["RESOURCES_DIR"]
    js_output_path = config["EXTRACT_FUNCTIONS_CACHE_DIR"]
    result_path = config["OUTPUT_DIR"]
    processed_projects_file = os.path.join(result_path, "processed_projects.txt")
    skipped_projects_file = os.path.join(result_path, "skipped_projects.txt")

    # 获取已处理的项目
    processed_projects = get_processed_projects(result_path)

    # 遍历待处理的目标文件夹下的所有子文件夹，他们都是NPM三方库
    projects = get_project_folders(target_dir)

    total_projects = len(projects)
    success_count = 0
    failure_count = 0
    skipped_count = 0

    # 创建进度条
    with tqdm(total=total_projects, desc="Processing projects", unit="project") as pbar:
        for project in projects:
            project_folder = project['path']
            if project['path'] in processed_projects:
                pbar.update(1)
                success_count += 1
                pbar.set_postfix({"Success": success_count, "Failure": failure_count, "Skipped": skipped_count})
                continue

            try:
                # 检查项目文件夹是否为空
                if is_directory_empty(project_folder):
                    with open(skipped_projects_file, 'a', encoding='utf-8') as f:
                        f.write(f"{project_folder}\n")
                    print(f"Skipping empty directory: {project_folder}")
                    pbar.update(1)
                    skipped_count += 1
                    pbar.set_postfix({"Success": success_count, "Failure": failure_count, "Skipped": skipped_count})
                    continue

                # 处理项目
                p = GitRepositoryFactory.parser_js_git_repository(project)
                if p is None:
                    raise ValueError(f"Failed to parse git repository for {project_folder}. Is it a valid Git repository?")

                p.js_output_path = js_output_path
                modified_function = p.analysis_all_version_modified_function()
                history_no_diff_functions = p.history_no_diff_functions
                history_no_diff_functions = converion_history(history_no_diff_functions)
                version_mate_info, version_diff_function_mate_info, diff_function_info = conversion_data(p, modified_function)

                if not diff_function_info:
                    logging.warning(f"No diff_function_info generated for {project_folder}")

                # 获取当前处理的三方库名称，默认为项目文件夹的名字
                library_name = os.path.basename(project_folder)
                if project['type'] != "standalone":
                    library_name = f"{project['org']}/{library_name}"
                # 确保目录存在
                library_dir = os.path.join(result_path, library_name)
                os.makedirs(library_dir, exist_ok=True)

                # 写入结果
                write_json(history_no_diff_functions, os.path.join(library_dir, "history_no_diff_function.json"))
                write_json(version_diff_function_mate_info, os.path.join(library_dir, "version_diff_function_mate.json"))
                write_json(diff_function_info, os.path.join(library_dir, "diff_function_info.json"))
                write_json(version_mate_info, os.path.join(library_dir, "version_mate_info.json"))

                # 记录已处理的项目
                record_processed_project(project_folder, processed_projects_file)

                success_count += 1

            except Exception as e:
                print(f"[ERROR] Failed to process {project_folder}: {e}")
                failure_count += 1

            # 更新进度条
            pbar.update(1)
            pbar.set_postfix({"Success": success_count, "Failure": failure_count, "Skipped": skipped_count})

    print(f"Summary:")
    print(f"  Total projects: {total_projects}")
    print(f"  Success: {success_count}")
    print(f"  Failure: {failure_count}")
    print(f"  Skipped: {skipped_count}")

if __name__ == '__main__':
    main()